﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;
using System.IO;
using System.Xml;
using System.ServiceModel.Syndication;
using Microsoft.Phone.Tasks;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Microsoft.Phone.Net.NetworkInformation;
using QuickWeb.Resources;

namespace QuickWeb
{
    public partial class RSSNews : PhoneApplicationPage
    {

        class ImageToDownload {
            public Uri uri;
            public int feedItemIndex = -1;
        }

        private ProgressIndicator progressBar;
        private int feedIDSelected = 0;
        private FeedsStoredContext storedFeedsDB;
        private FeedStored feedToRead;
        RSSTextTrimmer rssTrimmer;
        AppSettings settings = new AppSettings();
        private bool contentLoaded = false;


        private ClipsStoredContext storedClipsDB;
        private ObservableCollection<ClipStored> _ClipsStoredItems;
        public ObservableCollection<ClipStored> ClipsStoredItems
        {
            get
            {
                return _ClipsStoredItems;
            }
            set
            {
                if (_ClipsStoredItems != value)
                {
                    _ClipsStoredItems = value;
                    NotifyPropertyChanged("ClipsStoredItems");
                }
            }
        }



        public RSSNews()
        {
            InitializeComponent();
            rssTrimmer = new RSSTextTrimmer();
            storedFeedsDB = new FeedsStoredContext(FeedsStoredContext.DBConnectionString);
            storedClipsDB = new ClipsStoredContext(ClipsStoredContext.DBConnectionString);
            this.DataContext = this;
            progressBar = new ProgressIndicator();
            progressBar.IsVisible = true;
            SystemTray.SetProgressIndicator(this, progressBar);
            
        }

        private void showMessage(string msg)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                // Showing the exact error message is useful for debugging. In a finalized application, 
                // output a friendly and applicable string to the user instead. 
                MessageBox.Show(msg);                
            });
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (contentLoaded) {
                return;
            }

            string msg = "";
            if (NavigationContext.QueryString.TryGetValue("msg", out msg))
            {
                progressBar.Text = AppResources.loading;
                progressBar.IsIndeterminate = true;
                feedIDSelected = Convert.ToInt32(msg);
            }
            else
            {
                progressBar.Text = AppResources.errorTryAgain;
                progressBar.IsIndeterminate = false;
                return;
            }
            feedToRead = storedFeedsDB.items.First(i => i.FeedSourceID == feedIDSelected);
            if(feedToRead==null){
                progressBar.Text = AppResources.errorTryAgain;
                progressBar.IsIndeterminate = false;
                return;
            }
            //ya tenemos el item
            WebClient downloader = new WebClient();
            downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(feedDownloadStringCompleted);
            bool error = false;
            Uri feedUri = null;
            string readingURL = feedToRead.Source;
            try
            {
                feedUri = new Uri(readingURL);
            }
            catch (Exception ex)
            {
                error = true;
            }
            if (error || (feedUri == null))
            {
                progressBar.Text = AppResources.InvalidAddress;
                progressBar.IsIndeterminate = false;
                return;
            }
            downloader.DownloadStringAsync(feedUri);



            var clipsInDB = from ClipStored item in storedClipsDB.items
                            select item;
            ClipsStoredItems = new ObservableCollection<ClipStored>(clipsInDB);
            


            base.OnNavigatedTo(e);

            
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            //Guardar los resultados a la base de datos
            storedClipsDB.SubmitChanges();
        }

        private void feedDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                progressBar.IsIndeterminate = false;//Indicador de que se esta cargando contenido                   
                progressBar.Text = AppResources.noAvailableData;
            }
            else
            {
                // Save the feed into the State property in case the application is tombstoned. 
                analizeReceivedSourceInfo(e);    
            }
        }

        private void analizeReceivedSourceInfo(DownloadStringCompletedEventArgs e)
        {
            
            StringReader stringReader = new StringReader(e.Result);
            XmlReader xmlReader = XmlReader.Create(stringReader);
            SyndicationFeed feedReaded = SyndicationFeed.Load(xmlReader);
            Random rnd = new Random();
            FeedArticleDataList elementsReaded = new FeedArticleDataList();
            var cultureInfo = CultureInfo.CurrentCulture;
            RelativeTimeConverter timeTextConverter = new RelativeTimeConverter();
            foreach (var item in feedReaded.Items)
            {
                FeedArticleData article = new FeedArticleData();
                if (item.Title!=null)
                {
                    article.Title = item.Title.Text;
                }
                if (item.Summary!=null)
                {
                    object maxPreviLength = null;
                    int mpl = settings.ShowPreviewMaxLength;
                    if(mpl==0){
                        maxPreviLength = 200;
                    }else if(mpl==1){
                        maxPreviLength = 500;
                    }else{
                        maxPreviLength = -1;
                    }
                    
                    article.PreviewDescription = rssTrimmer.Convert(item.Summary.Text, null, maxPreviLength, null) as string;
                    //article.ImagePath = item.Summary.Text.Split('<')[5].Replace("img src='", "").Replace("' border='0' />", "");
                    //jpg
                    int LoadFeedsImages = settings.LoadFeedsImages;
                    bool loadImagesQ = false;
                    if (LoadFeedsImages == 1)
                    {
                        loadImagesQ = true;
                    }                    
                    if(loadImagesQ){
                        article.ImagePath = (Regex.Match(item.Summary.Text, "<img(.*?) src=\"(.*?)\"[^>]*>").Groups[2].Value);                                            
                    }
                }
                if (item.Links.Count > 0)
                {
                    article.uri = item.Links.FirstOrDefault().Uri;
                }
                if(item.PublishDate!=null){

                    article.PublicationDateAndAuthor = timeTextConverter.Convert(item.PublishDate.LocalDateTime, null, null, cultureInfo) as string;
                }
                if(item.Authors.Count>0){
                    if (article.PublicationDateAndAuthor.Length>0)
                    {
                        article.PublicationDateAndAuthor+=", ";
                    }
                    article.PublicationDateAndAuthor = "by "+item.Authors.FirstOrDefault().Name;
                }                
                
                elementsReaded.Add(article);
            }
            progressBar.Text = "";
            progressBar.IsIndeterminate = false;
            FeedsSourceList.ItemsSource = elementsReaded;
            FeedSourceTitle.Text = feedReaded.Title.Text;
            contentLoaded = true;
            
        }

        private void OpenInBrowser_Click(object sender, RoutedEventArgs e)
        {
           
        }

        private void AddToReadingList_Click(object sender, RoutedEventArgs e)
        {
            var it = sender as MenuItem;
            if (it != null)
            {
                var article = it.DataContext as FeedArticleData;
                ClipStored clipToStore = new ClipStored();
                clipToStore.Title = article.Title;
                clipToStore.Description = article.PreviewDescription;
                clipToStore.Link = article.uri.OriginalString;
                ClipsStoredItems.Add(clipToStore);
                storedClipsDB.items.InsertOnSubmit(clipToStore);  
            }

            
            
        }

        private void FeedsSourceList_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (FrameworkElement)e.OriginalSource;
            var feed = ((FeedArticleData)item.DataContext);
            //Uri uri = new Uri(feed.Link);
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            webBrowserTask.Uri = feed.uri;
            webBrowserTask.Show();
        }

        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        private void CheckWebsiteButton_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            webBrowserTask.Uri = new Uri(feedToRead.Link);
            webBrowserTask.Show();
        }

    }
}